package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.TencentSmsConfig;
import com.ruoyi.system.service.ITencentSmsService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 腾讯云短信 业务层处理
 */
@Service
public class TencentSmsServiceImpl implements ITencentSmsService {

    private static final Logger log = LoggerFactory.getLogger(TencentSmsServiceImpl.class);

    @Resource
    private TencentSmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param mobile 手机号
     * @param code 短信验证码
     * @param expireMinutes 短信验证码过期时间，单位分钟
     */
    @Override
    public void sendSms(String mobile, String code, int expireMinutes) {
        String[] phoneNumbers = {"+86" + mobile};
        // 验证码和有效期(分钟)
        String[] templateParams = {code, String.valueOf(expireMinutes)};
        Credential credential = new Credential(smsConfig.getSecretId(), smsConfig.getSecretKey());
        SmsClient client = new SmsClient(credential, smsConfig.getRegion());
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppId(smsConfig.getSdkAppId());
        req.setSignName(smsConfig.getSignName());
        req.setTemplateId(smsConfig.getTemplateId());
        req.setPhoneNumberSet(phoneNumbers);
        req.setTemplateParamSet(templateParams);
        try {
            SendSmsResponse resp = client.SendSms(req);
            log.info("短信发送返回结果：{}", SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("短信发送异常", e);
        }
    }
}
